<?php
  session_start(); // start up your PHP session!
  // create short variable names
  $uname = $_SESSION['uname'];
  $upass = $_POST['oldpass'];
  $newpass = $_POST['newpass1'];
  $newpass2 = $_POST['newpass2'];
?>
<html>
<head>
  <title>Password Maintenance</title>
</head>
<body>
<h3>Password Change</h3>
<?php
    $fp = fopen('user.cfg', 'r');
	if($fp)
	{    
	    $arr = array();
		$auth = 0;
	    while(!feof($fp))
		{
			$name = stream_get_line( $fp, 1024, "\r\n" );
					
			if (!$name)
      {
        break;
      }
			
			$pass = stream_get_line( $fp, 1024, "\r\n" );		
			
			$arr[$name] = $pass;
			if($uname==$name && $upass==$pass)
			{
				$auth = 1;
			}		
		}
		fclose($fp);

		if($auth == 1)
		{
		   if($newpass == $newpass2)
		   {
		      $arr[$uname] = $newpass;
			  $fp = fopen('user.cfg', 'w');
			  if($fp)
			  {
			     foreach($arr as $key => $value)
				 {
					fwrite($fp, $key."\r\n".$value."\r\n");
				 }
				 fclose($fp);
				 
				 $_SESSION['message'] = "Passwords are changed successfully.";
				 header('Location: ChangePassword.php');				
			  }
			  else
			  {
				 $_SESSION['message'] = "Cannot access the server.";
				 header('Location: ChangePassword.php');
			  }
		   }
		   else
		   {
		    $_SESSION['message'] = "New Password verification does not match.";
        header('Location: ChangePassword.php');
		   }

		}
		else
		{
		  $_SESSION['message'] = "Authentication failed.";
			header('Location: ChangePassword.php');
		}
	}
	else
	{
	  $_SESSION['message'] = "Cannot access the server.";
		header('Location: ChangePassword.php');
	}


?>
</body>
</html>